
#include "list.h"

DLINKLIST *llist_create(int initsize) 
{
	DLINKLIST *newlist;
	newlist = malloc(sizeof(*newlist));
	if(!newlist)
		return NULL;
	newlist->size = initsize;
	newlist->head.data = NULL;
	newlist->head.prev = &newlist->head;
	newlist->head.next = &newlist->head;
	return newlist;
}
void llist_destroy(DLINKLIST* ptr)
{
	struct  dllist_node_st * cur, * next;
	for (cur = ptr->head.next; cur != &ptr->head; cur = next)
	{
		next = cur->next;
		free(cur->data);
		free(cur);
	}
	free(ptr);
}
int llist_insert(DLINKLIST * ptr, const void* data, int mode)
{
	struct dllist_node_st *newnode;
	newnode = malloc(sizeof(*newnode));
	if (!newnode)
		return -1;
	newnode->data = malloc(ptr->size);
	if (!newnode->data)
		return -2;
	memcpy(newnode->data, data, ptr->size);
	if (mode == FORWARD)
	{
		newnode->next = ptr->head.next;
		newnode->prev = &ptr->head;
		

	}
	else if (mode == BACKWARD)
	{
		newnode->prev = ptr->head.prev;
		newnode->next = &ptr->head;
		
	}
	else
		return -3;
	newnode->prev->next = newnode;
	newnode->next->prev = newnode;
	return 0;
}
void llist_travel(DLINKLIST*ptr, llist_op *op)
{
	struct  dllist_node_st* cur, * next;
	for (cur = ptr->head.next; cur != &ptr->head; cur = cur->next)
	{
		op(cur->data);
	}
}